notebooks/community/migration/UJ8 AutoML for natural language with Vertex AI - Text Sentiment Analysis.ipynb (2,355 lines of code) (raw):
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Sf2Z7mlw1siQ"
},
"outputs": [],
"source": [
"# Copyright 2021 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_title:migration,automl,icn"
},
"source": [
"# Vertex AI AutoML text sentiment analysis model\n",
"\n",
"## Installation\n",
"\n",
"Install the latest (preview) version of Vertex SDK."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7dxB6-B0JjkG"
},
"outputs": [],
"source": [
"! pip3 install -U google-cloud-aiplatform --user"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Iddo-8HmJjkH"
},
"source": [
"Install the Google *cloud-storage* library as well."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xHvi6EFSJjkH"
},
"outputs": [],
"source": [
"! pip3 install google-cloud-storage"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ktRTgB8DJjkI"
},
"source": [
"### Restart the Kernel\n",
"\n",
"Once you've installed the Vertex SDK and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "x1g4mBdlJjkI"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"if not os.getenv(\"AUTORUN\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
"\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4yZl1w-T6H1Q"
},
"source": [
"## Before you begin\r\n",
"\r\n",
"### GPU run-time\r\n",
"\r\n",
"*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\r\n",
"\r\n",
"### Set up your GCP project\r\n",
"\r\n",
"**The following steps are required, regardless of your notebook environment.**\r\n",
"\r\n",
"1. [Select or create a GCP project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\r\n",
"\r\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\r\n",
"\r\n",
"3. [Enable the Vertex APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\r\n",
"\r\n",
"4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in Google Cloud Notebooks.\r\n",
"\r\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\r\n",
"Cloud SDK uses the right project for all the commands in this notebook.\r\n",
"\r\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eidueLnCJjkJ"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "s__D9HcZ1siZ"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "0UfsdLCEJjkJ"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jT0fijejJjkK"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend when possible, to choose the region closest to you. \n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You cannot use a Multi-Regional Storage bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see [Region support for Vertex AI services](https://cloud.google.com/vertex-ai/docs/general/locations)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "CTBlncfrJjkK"
},
"outputs": [],
"source": [
"REGION = \"us-central1\" # @param {type: \"string\"}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "J_croPBoJjkK"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KKxStk5bJjkL"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Wx4DX8I07d-_"
},
"source": [
"### Authenticate your GCP account\r\n",
"\r\n",
"**If you are using Google Cloud Notebooks**, your environment is already\r\n",
"authenticated. Skip this step.\r\n",
"\r\n",
"*Note: If you are on an Vertex notebook and run the cell, the cell knows to skip executing the authentication steps.*"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "chybg3Ap_i_2"
},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"\n",
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your Google Cloud account. This provides access\n",
"# to your Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"# If on Vertex, then don't execute this code\n",
"if not os.path.exists(\"/opt/deeplearning/metadata/env_version\"):\n",
" if \"google.colab\" in sys.modules:\n",
" from google.colab import auth as google_auth\n",
"\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this tutorial in a notebook locally, replace the string\n",
" # below with the path to your service account key and run this cell to\n",
" # authenticate your Google Cloud account.\n",
" else:\n",
" %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json\n",
"\n",
" # Log in to your account on Google Cloud\n",
" ! gcloud auth login"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MDUAZaN3JjkL"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" # @param {type:\"string\"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yU6VuylGJjkM"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QVRixM4oJjkM"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION gs://$BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Mi-Pdh6QJjkN"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aqDptKpYJjkN"
},
"outputs": [],
"source": [
"! gsutil ls -al gs://$BUCKET_NAME"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fR9geV9pJjkO"
},
"source": [
"### Set up variables\n",
"\n",
"Next, set up some variables used throughout the tutorial.\n",
"### Import libraries and define constants"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hIHTX-pkJjkO"
},
"source": [
"#### Import Vertex SDK\n",
"\n",
"Import the Vertex SDK into our Python environment."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qrSkIKVgJjkO"
},
"outputs": [],
"source": [
"import json\n",
"import os\n",
"import sys\n",
"import time\n",
"\n",
"from google.cloud.aiplatform import gapic as aip\n",
"from google.protobuf import json_format\n",
"from google.protobuf.json_format import MessageToJson\n",
"from google.protobuf.struct_pb2 import Struct, Value"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "lbv411XjJjkP"
},
"source": [
"#### Vertex AI constants\n",
"\n",
"Setup up the following constants for Vertex AI:\n",
"\n",
"- `API_ENDPOINT`: The Vertex AI API service endpoint for dataset, model, job, pipeline and endpoint services.\n",
"- `PARENT`: The Vertex AI location root path for dataset, model and endpoint resources."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Gx8Eos8PJjkP"
},
"outputs": [],
"source": [
"# API Endpoint\n",
"API_ENDPOINT = \"us-central1-aiplatform.googleapis.com\"\n",
"\n",
"# Vertex AI location root path for your dataset, model and endpoint resources\n",
"PARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "4x_t-MWnJjkQ"
},
"source": [
"#### AutoML constants\n",
"\n",
"Next, setup constants unique to AutoML Text Entity Extraction datasets and training:\n",
"\n",
"- Dataset Schemas: Tells the managed dataset service which type of dataset it is.\n",
"- Data Labeling (Annotations) Schemas: Tells the managed dataset service how the data is labeled (annotated).\n",
"- Dataset Training Schemas: Tells the Vertex AI Pipelines service the task (e.g., classification) to train the model for."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nmzhH42tJjkQ"
},
"outputs": [],
"source": [
"# Text Dataset type\n",
"TEXT_SCHEMA = \"google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml\"\n",
"# Text Labeling type\n",
"IMPORT_SCHEMA_TEXT_SENTIMENT = \"gs://google-cloud-aiplatform/schema/dataset/ioformat/text_sentiment_io_format_1.0.0.yaml\"\n",
"# Text Training task\n",
"TRAINING_TEXT_SENTIMENT_SCHEMA = \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_sentiment_1.0.0.yaml\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "R7P3MRNgJjkQ"
},
"source": [
"## Clients\n",
"\n",
"The Vertex SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (Vertex).\n",
"\n",
"You will use several clients in this tutorial, so set them all up upfront.\n",
"\n",
"- Dataset Service for managed datasets.\n",
"- Model Service for managed models.\n",
"- Pipeline Service for training.\n",
"- Endpoint Service for deployment.\n",
"- Job Service for batch jobs and custom training.\n",
"- Prediction Service for serving. *Note*: Prediction has a different service endpoint."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kt8j_ey4JjkR"
},
"outputs": [],
"source": [
"# client options same for all services\n",
"client_options = {\"api_endpoint\": API_ENDPOINT}\n",
"\n",
"\n",
"def create_dataset_client():\n",
" client = aip.DatasetServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_model_client():\n",
" client = aip.ModelServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_pipeline_client():\n",
" client = aip.PipelineServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_endpoint_client():\n",
" client = aip.EndpointServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_prediction_client():\n",
" client = aip.PredictionServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"def create_job_client():\n",
" client = aip.JobServiceClient(client_options=client_options)\n",
" return client\n",
"\n",
"\n",
"clients = {}\n",
"clients[\"dataset\"] = create_dataset_client()\n",
"clients[\"model\"] = create_model_client()\n",
"clients[\"pipeline\"] = create_pipeline_client()\n",
"clients[\"endpoint\"] = create_endpoint_client()\n",
"clients[\"prediction\"] = create_prediction_client()\n",
"clients[\"job\"] = create_job_client()\n",
"\n",
"for client in clients.items():\n",
" print(client)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "import_file:flowers,csv,icn"
},
"outputs": [],
"source": [
"IMPORT_FILE = \"gs://cloud-samples-data/language/claritin-split.csv\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cBgFrDD1_i__"
},
"outputs": [],
"source": [
"! gsutil cat $IMPORT_FILE | head -n 10"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_create:migration,new,request"
},
"source": [
"*Example output*:\n",
"```\n",
"TRAINING,@freewrytin God is way too good for Claritin,2,4\n",
"TRAINING,I need Claritin. So bad. When did I become cursed with allergies?,3,4\n",
"TRAINING,Thank god for Claritin.,4,4\n",
"TRAINING,\"And what's worse is that I reached my 3-day limit on the nose spray yesterday, which means I have to rely on Claritin.\",2,4\n",
"TRAINING,Time to take some Claritin or Allegra or something. I need my voice,3,4\n",
"TRAINING,Oh my RT @imsydneycharles: I just want it to be on record somewhere that I took Claritin and Benadryl together...just in case I pass out,2,4\n",
"TRAINING,Bouta take a Claritin _ÛªÛ_Ûª_ÛªÌâ FML !!,3,4\n",
"TRAINING,Commander Loratadine Generic A Sarcelles: Commander Loratadine Generic A Sarcelles Claritin =Ûª_Ûª__ http://t.co/mOleL8AM,2,4\n",
"TRAINING,\"Zyrtec, Claritin, Suddafed, Nasal Spray.. I feel like a drug addict taking these Allergy medicine. Please Allergy season.. DISAPPEAR!!\",1,4\n",
"TRAINING,\"Ûª_Ûª_ÛªÕ@SheLovesThatD: If she has allergies, give her the Claritin D.Ûª_Ûª_Ì_å @Sweeno_thakid41 @B_Original16 @luke_CYwalker14\",3,4\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_create_dataset:migration"
},
"source": [
"## Create a dataset"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b0J_eRSR1sih"
},
"source": [
"### Prepare data"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_datasets_create:migration,new"
},
"source": [
"### [projects.locations.datasets.create](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.datasets/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UwqJ-Ua-1sii"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "BsQTgqv41sij"
},
"outputs": [],
"source": [
"DATA_SCHEMA = TEXT_SCHEMA\n",
"\n",
"dataset = {\n",
" \"display_name\": \"claritin_\" + TIMESTAMP,\n",
" \"metadata_schema_uri\": \"gs://\" + DATA_SCHEMA,\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.CreateDatasetRequest(parent=PARENT, dataset=dataset).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sPupiwqN_jAB"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"dataset\": {\n",
" \"displayName\": \"claritin_20210301212135\",\n",
" \"metadataSchemaUri\": \"gs://google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml\"\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8Vw-Ht8R1sij"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ctso28tq1sij"
},
"outputs": [],
"source": [
"request = clients[\"dataset\"].create_dataset(parent=PARENT, dataset=dataset)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "t2VmcwXf1sij"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7X0tEzLW1sik"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sPupiwqN_jAB"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/datasets/3047617533776494592\",\n",
" \"displayName\": \"claritin_20210301212135\",\n",
" \"metadataSchemaUri\": \"gs://google-cloud-aiplatform/schema/dataset/metadata/text_1.0.0.yaml\",\n",
" \"labels\": {\n",
" \"aiplatform.googleapis.com/dataset_metadata_schema\": \"TEXT\"\n",
" },\n",
" \"metadata\": {\n",
" \"dataItemSchemaUri\": \"gs://google-cloud-aiplatform/schema/dataset/dataitem/text_1.0.0.yaml\"\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dataset_id:migration,new,response"
},
"outputs": [],
"source": [
"# The full unique ID for the dataset\n",
"dataset_id = result.name\n",
"# The short numeric ID for the dataset\n",
"dataset_short_id = dataset_id.split(\"/\")[-1]\n",
"\n",
"print(dataset_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_datasets_import:migration,new"
},
"source": [
"### [projects.locations.datasets.import](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.datasets/import)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FrIGGdbC1sik"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "L4UZJnOM1sik"
},
"outputs": [],
"source": [
"LABEL_SCHEMA = IMPORT_SCHEMA_TEXT_SENTIMENT\n",
"\n",
"import_config = {\n",
" \"gcs_source\": {\"uris\": [IMPORT_FILE]},\n",
" \"import_schema_uri\": LABEL_SCHEMA,\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.ImportDataRequest(name=dataset_id, import_configs=[import_config]).__dict__[\n",
" \"_pb\"\n",
" ]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sPupiwqN_jAB"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/datasets/3047617533776494592\",\n",
" \"importConfigs\": [\n",
" {\n",
" \"gcsSource\": {\n",
" \"uris\": [\n",
" \"gs://cloud-samples-data/language/claritin-split.csv\"\n",
" ]\n",
" },\n",
" \"importSchemaUri\": \"gs://google-cloud-aiplatform/schema/dataset/ioformat/text_sentiment_io_format_1.0.0.yaml\"\n",
" }\n",
" ]\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "klKZuShs1sik"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KURUWPTj1sil"
},
"outputs": [],
"source": [
"request = clients[\"dataset\"].import_data(\n",
" name=dataset_id, import_configs=[import_config]\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ggs4F4QJ1sil"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4amvwklf1sil"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sPupiwqN_jAB"
},
"source": [
"*Example output*:\n",
"```\n",
"{}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_create_and_deploy_model:migration"
},
"source": [
"## Train a model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0oqIBOSnJjkW"
},
"source": [
"### [projects.locations.trainingPipelines.create](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.trainingPipelines/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rqTHZlwM1sil"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Y2EnBqsW1sim"
},
"outputs": [],
"source": [
"TRAINING_SCHEMA = TRAINING_TEXT_SENTIMENT_SCHEMA\n",
"\n",
"task = Value(struct_value=Struct(fields={\"sentiment_max\": Value(number_value=4)}))\n",
"\n",
"training_pipeline = {\n",
" \"display_name\": \"claritin_\" + TIMESTAMP,\n",
" \"input_data_config\": {\"dataset_id\": dataset_short_id},\n",
" \"model_to_upload\": {\"display_name\": \"claritin_\" + TIMESTAMP},\n",
" \"training_task_definition\": TRAINING_SCHEMA,\n",
" \"training_task_inputs\": task,\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.CreateTrainingPipelineRequest(\n",
" parent=PARENT,\n",
" training_pipeline=training_pipeline,\n",
" ).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sPupiwqN_jAB"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"trainingPipeline\": {\n",
" \"displayName\": \"claritin_20210301212135\",\n",
" \"inputDataConfig\": {\n",
" \"datasetId\": \"3047617533776494592\"\n",
" },\n",
" \"trainingTaskDefinition\": \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_sentiment_1.0.0.yaml\",\n",
" \"trainingTaskInputs\": {\n",
" \"sentiment_max\": 4.0\n",
" },\n",
" \"modelToUpload\": {\n",
" \"displayName\": \"claritin_20210301212135\"\n",
" }\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ynb6GJWQ1sim"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "LahVyHQD1sim"
},
"outputs": [],
"source": [
"request = clients[\"pipeline\"].create_training_pipeline(\n",
" parent=PARENT, training_pipeline=training_pipeline\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xES6wtah1sim"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Kw_d_K7j1sim"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sPupiwqN_jAB"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/trainingPipelines/5293990158067040256\",\n",
" \"displayName\": \"claritin_20210301212135\",\n",
" \"inputDataConfig\": {\n",
" \"datasetId\": \"3047617533776494592\"\n",
" },\n",
" \"trainingTaskDefinition\": \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_sentiment_1.0.0.yaml\",\n",
" \"trainingTaskInputs\": {\n",
" \"sentimentMax\": 4.0\n",
" },\n",
" \"modelToUpload\": {\n",
" \"displayName\": \"claritin_20210301212135\"\n",
" },\n",
" \"state\": \"PIPELINE_STATE_PENDING\",\n",
" \"createTime\": \"2021-03-01T21:32:03.085444Z\",\n",
" \"updateTime\": \"2021-03-01T21:32:03.085444Z\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "54bab5051996"
},
"outputs": [],
"source": [
"# The full unique ID for the training pipeline\n",
"training_pipeline_id = request.name\n",
"# The short numeric ID for the training pipeline\n",
"training_pipeline_short_id = training_pipeline_id.split(\"/\")[-1]\n",
"\n",
"print(training_pipeline_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "QJsV1xoSJjkW"
},
"source": [
"### [projects.locations.trainingPipelines.get](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.trainingPipelines/get)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wZZJzTBo1sin"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qBKk5fXY1sin"
},
"outputs": [],
"source": [
"request = clients[\"pipeline\"].get_training_pipeline(name=training_pipeline_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "RCLZYC_T1sin"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "P8qJbudB1sin"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sPupiwqN_jAB"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/trainingPipelines/5293990158067040256\",\n",
" \"displayName\": \"claritin_20210301212135\",\n",
" \"inputDataConfig\": {\n",
" \"datasetId\": \"3047617533776494592\"\n",
" },\n",
" \"trainingTaskDefinition\": \"gs://google-cloud-aiplatform/schema/trainingjob/definition/automl_text_sentiment_1.0.0.yaml\",\n",
" \"trainingTaskInputs\": {\n",
" \"sentimentMax\": 4.0\n",
" },\n",
" \"modelToUpload\": {\n",
" \"displayName\": \"claritin_20210301212135\"\n",
" },\n",
" \"state\": \"PIPELINE_STATE_PENDING\",\n",
" \"createTime\": \"2021-03-01T21:32:03.085444Z\",\n",
" \"updateTime\": \"2021-03-01T21:32:03.085444Z\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "trainingpipelines_get:migration,new,wait"
},
"outputs": [],
"source": [
"while True:\n",
" response = clients[\"pipeline\"].get_training_pipeline(name=training_pipeline_id)\n",
" if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:\n",
" print(\"Training job has not completed:\", response.state)\n",
" if response.state == aip.PipelineState.PIPELINE_STATE_FAILED:\n",
" break\n",
" else:\n",
" model_id = response.model_to_upload.name\n",
" print(\"Training Time:\", response.end_time - response.start_time)\n",
" break\n",
" time.sleep(20)\n",
"\n",
"print(model_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_evaluate_the_model:migration"
},
"source": [
"## Evaluate the model"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BJNzhELXJjkY"
},
"source": [
"### [projects.locations.models.evaluations.list](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.models.evaluations/list)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HfPQn-dg1sio"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "cK7Vpv9i1sio"
},
"outputs": [],
"source": [
"request = clients[\"model\"].list_model_evaluations(parent=model_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "OQDH5S_d1sio"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "prEvwExMmDy8"
},
"outputs": [],
"source": [
"model_evaluations = [json.loads(MessageToJson(mel.__dict__[\"_pb\"])) for mel in request]\n",
"\n",
"# The evaluation slice\n",
"evaluation_slice = request.model_evaluations[0].name\n",
"\n",
"print(json.dumps(model_evaluations, indent=2))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sPupiwqN_jAB"
},
"source": [
"*Example output*:\n",
"```\n",
"[\n",
" {\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/5497364624833511424/evaluations/412684097299677184\",\n",
" \"metricsSchemaUri\": \"gs://google-cloud-aiplatform/schema/modelevaluation/text_sentiment_metrics_1.0.0.yaml\",\n",
" \"metrics\": {\n",
" \"linearKappa\": 0.4001057,\n",
" \"quadraticKappa\": 0.48378703,\n",
" \"precision\": 0.59030837,\n",
" \"confusionMatrix\": {\n",
" \"rows\": [\n",
" [\n",
" 3.0,\n",
" 4.0,\n",
" 1.0,\n",
" 1.0,\n",
" 0.0\n",
" ],\n",
" [\n",
" 2.0,\n",
" 19.0,\n",
" 25.0,\n",
" 18.0,\n",
" 0.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 10.0,\n",
" 72.0,\n",
" 57.0,\n",
" 0.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 16.0,\n",
" 34.0,\n",
" 169.0,\n",
" 5.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 0.0,\n",
" 2.0,\n",
" 11.0,\n",
" 5.0\n",
" ]\n",
" ],\n",
" \"annotationSpecs\": [\n",
" {\n",
" \"displayName\": \"0\",\n",
" \"id\": \"7302033741432487936\"\n",
" },\n",
" {\n",
" \"id\": \"1537426218398253056\",\n",
" \"displayName\": \"1\"\n",
" },\n",
" {\n",
" \"displayName\": \"2\",\n",
" \"id\": \"6149112236825640960\"\n",
" },\n",
" {\n",
" \"displayName\": \"3\",\n",
" \"id\": \"3843269227611947008\"\n",
" },\n",
" {\n",
" \"displayName\": \"4\",\n",
" \"id\": \"8454955246039334912\"\n",
" }\n",
" ]\n",
" },\n",
" \"meanAbsoluteError\": 0.4955947,\n",
" \"f1Score\": 0.59030837,\n",
" \"recall\": 0.59030837,\n",
" \"meanSquaredError\": 0.67180616\n",
" },\n",
" \"createTime\": \"2021-03-02T01:41:13.130713Z\",\n",
" \"sliceDimensions\": [\n",
" \"annotationSpec\"\n",
" ]\n",
" }\n",
"]\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wr2JuU5nJjka"
},
"source": [
"### [projects.locations.models.evaluations.get](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.models.evaluations/get)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kh15ZsBj1sip"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eRbV7hzH1sip"
},
"outputs": [],
"source": [
"request = clients[\"model\"].get_model_evaluation(name=evaluation_slice)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KQLWoPmU1sip"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fo2fAEf61sip"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "sPupiwqN_jAB"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/5497364624833511424/evaluations/412684097299677184\",\n",
" \"metricsSchemaUri\": \"gs://google-cloud-aiplatform/schema/modelevaluation/text_sentiment_metrics_1.0.0.yaml\",\n",
" \"metrics\": {\n",
" \"meanSquaredError\": 0.67180616,\n",
" \"linearKappa\": 0.4001057,\n",
" \"precision\": 0.59030837,\n",
" \"recall\": 0.59030837,\n",
" \"confusionMatrix\": {\n",
" \"annotationSpecs\": [\n",
" {\n",
" \"id\": \"7302033741432487936\",\n",
" \"displayName\": \"0\"\n",
" },\n",
" {\n",
" \"id\": \"1537426218398253056\",\n",
" \"displayName\": \"1\"\n",
" },\n",
" {\n",
" \"displayName\": \"2\",\n",
" \"id\": \"6149112236825640960\"\n",
" },\n",
" {\n",
" \"id\": \"3843269227611947008\",\n",
" \"displayName\": \"3\"\n",
" },\n",
" {\n",
" \"id\": \"8454955246039334912\",\n",
" \"displayName\": \"4\"\n",
" }\n",
" ],\n",
" \"rows\": [\n",
" [\n",
" 3.0,\n",
" 4.0,\n",
" 1.0,\n",
" 1.0,\n",
" 0.0\n",
" ],\n",
" [\n",
" 2.0,\n",
" 19.0,\n",
" 25.0,\n",
" 18.0,\n",
" 0.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 10.0,\n",
" 72.0,\n",
" 57.0,\n",
" 0.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 16.0,\n",
" 34.0,\n",
" 169.0,\n",
" 5.0\n",
" ],\n",
" [\n",
" 0.0,\n",
" 0.0,\n",
" 2.0,\n",
" 11.0,\n",
" 5.0\n",
" ]\n",
" ]\n",
" },\n",
" \"meanAbsoluteError\": 0.4955947,\n",
" \"quadraticKappa\": 0.48378703,\n",
" \"f1Score\": 0.59030837\n",
" },\n",
" \"createTime\": \"2021-03-02T01:41:13.130713Z\",\n",
" \"sliceDimensions\": [\n",
" \"annotationSpec\"\n",
" ]\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8T8qLCuR1sip"
},
"source": [
"## Make batch predictions"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c660ee11e92e"
},
"source": [
"### Make the batch input file\n",
"\n",
"Let's now make a batch input file, which you will store in your local Cloud Storage bucket. The batch input file can be either CSV or JSONL. You will use JSONL in this tutorial. For JSONL file, you make one dictionary entry per line for each data item (instance). The dictionary contains the key/value pairs:\n",
"\n",
"- `content`: The Cloud Storage path to the image.\n",
"- `mime_type`: The content type. In our example, it is an `test/plain` file."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bPax2DdN1siq"
},
"outputs": [],
"source": [
"import json\n",
"\n",
"import tensorflow as tf\n",
"\n",
"test_data = ! gsutil cat $IMPORT_FILE | head -n1\n",
"\n",
"test_item = str(test_data[0]).split(\",\")[1]\n",
"test_label = str(test_data[0]).split(\",\")[2]\n",
"\n",
"gcs_test_item = \"gs://\" + BUCKET_NAME + \"/test.txt\"\n",
"with tf.io.gfile.GFile(gcs_test_item, \"w\") as f:\n",
" f.write(test_item + \"\\n\")\n",
"\n",
"gcs_input_uri = \"gs://\" + BUCKET_NAME + \"/test.jsonl\"\n",
"with tf.io.gfile.GFile(gcs_input_uri, \"w\") as f:\n",
" data = {\"content\": gcs_test_item, \"mime_type\": \"text/plain\"}\n",
" f.write(json.dumps(data) + \"\\n\")\n",
"\n",
"! gsutil cat $gcs_input_uri\n",
"! gsutil cat $gcs_test_item"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\"content\": \"gs://migration-ucaip-trainingaip-20210301212135/test.txt\", \"mime_type\": \"text/plain\"}\n",
"@freewrytin God is way too good for Claritin\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tnqYDtYF1siq"
},
"source": [
"### [projects.locations.batchPredictionJobs.create](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.batchPredictionJobs/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ozaMOwdNJjkT"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "XXYA8Ns21siq"
},
"outputs": [],
"source": [
"batch_prediction_job = {\n",
" \"display_name\": \"claritin_\" + TIMESTAMP,\n",
" \"model\": model_id,\n",
" \"input_config\": {\n",
" \"instances_format\": \"jsonl\",\n",
" \"gcs_source\": {\"uris\": [gcs_input_uri]},\n",
" },\n",
" \"output_config\": {\n",
" \"predictions_format\": \"jsonl\",\n",
" \"gcs_destination\": {\n",
" \"output_uri_prefix\": \"gs://\" + f\"{BUCKET_NAME}/batch_output/\"\n",
" },\n",
" },\n",
" \"dedicated_resources\": {\n",
" \"machine_spec\": {\"machine_type\": \"n1-standard-2\", \"accelerator_count\": 0},\n",
" \"starting_replica_count\": 1,\n",
" \"max_replica_count\": 1,\n",
" },\n",
"}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.CreateBatchPredictionJobRequest(\n",
" parent=PARENT, batch_prediction_job=batch_prediction_job\n",
" ).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"batchPredictionJob\": {\n",
" \"displayName\": \"claritin_20210301212135\",\n",
" \"model\": \"projects/116273516712/locations/us-central1/models/5497364624833511424\",\n",
" \"inputConfig\": {\n",
" \"instancesFormat\": \"jsonl\",\n",
" \"gcsSource\": {\n",
" \"uris\": [\n",
" \"gs://migration-ucaip-trainingaip-20210301212135/test.jsonl\"\n",
" ]\n",
" }\n",
" },\n",
" \"outputConfig\": {\n",
" \"predictionsFormat\": \"jsonl\",\n",
" \"gcsDestination\": {\n",
" \"outputUriPrefix\": \"gs://migration-ucaip-trainingaip-20210301212135/batch_output/\"\n",
" }\n",
" },\n",
" \"dedicatedResources\": {\n",
" \"machineSpec\": {\n",
" \"machineType\": \"n1-standard-2\"\n",
" },\n",
" \"startingReplicaCount\": 1,\n",
" \"maxReplicaCount\": 1\n",
" }\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NF7BDJ9v1siq"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "vNaCWhY91siq"
},
"outputs": [],
"source": [
"request = clients[\"job\"].create_batch_prediction_job(\n",
" parent=PARENT, batch_prediction_job=batch_prediction_job\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "n78sGHxZ1sir"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "VjX3nEZv1sir"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/batchPredictionJobs/3543215802926759936\",\n",
" \"displayName\": \"claritin_20210301212135\",\n",
" \"model\": \"projects/116273516712/locations/us-central1/models/5497364624833511424\",\n",
" \"inputConfig\": {\n",
" \"instancesFormat\": \"jsonl\",\n",
" \"gcsSource\": {\n",
" \"uris\": [\n",
" \"gs://migration-ucaip-trainingaip-20210301212135/test.jsonl\"\n",
" ]\n",
" }\n",
" },\n",
" \"outputConfig\": {\n",
" \"predictionsFormat\": \"jsonl\",\n",
" \"gcsDestination\": {\n",
" \"outputUriPrefix\": \"gs://migration-ucaip-trainingaip-20210301212135/batch_output/\"\n",
" }\n",
" },\n",
" \"state\": \"JOB_STATE_PENDING\",\n",
" \"completionStats\": {\n",
" \"incompleteCount\": \"-1\"\n",
" },\n",
" \"createTime\": \"2021-03-02T01:41:31.919764Z\",\n",
" \"updateTime\": \"2021-03-02T01:41:31.919764Z\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "7d448b1cc8c1"
},
"outputs": [],
"source": [
"# The fully qualified ID for the batch job\n",
"batch_job_id = request.name\n",
"# The short numeric ID for the batch job\n",
"batch_job_short_id = batch_job_id.split(\"/\")[-1]\n",
"\n",
"print(batch_job_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "mZ8NQGM31sir"
},
"source": [
"### [projects.locations.batchPredictionJobs.get](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.batchPredictionJobs/get)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zZOSE1961sir"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "kEMq5lPi1sir"
},
"outputs": [],
"source": [
"request = clients[\"job\"].get_batch_prediction_job(name=batch_job_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9cgeT_7B1sir"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OT3wuCUw1sis"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/batchPredictionJobs/3543215802926759936\",\n",
" \"displayName\": \"claritin_20210301212135\",\n",
" \"model\": \"projects/116273516712/locations/us-central1/models/5497364624833511424\",\n",
" \"inputConfig\": {\n",
" \"instancesFormat\": \"jsonl\",\n",
" \"gcsSource\": {\n",
" \"uris\": [\n",
" \"gs://migration-ucaip-trainingaip-20210301212135/test.jsonl\"\n",
" ]\n",
" }\n",
" },\n",
" \"outputConfig\": {\n",
" \"predictionsFormat\": \"jsonl\",\n",
" \"gcsDestination\": {\n",
" \"outputUriPrefix\": \"gs://migration-ucaip-trainingaip-20210301212135/batch_output/\"\n",
" }\n",
" },\n",
" \"state\": \"JOB_STATE_PENDING\",\n",
" \"completionStats\": {\n",
" \"incompleteCount\": \"-1\"\n",
" },\n",
" \"createTime\": \"2021-03-02T01:41:31.919764Z\",\n",
" \"updateTime\": \"2021-03-02T01:41:31.919764Z\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "3cdf7f0526ec"
},
"outputs": [],
"source": [
"def get_latest_predictions(gcs_out_dir):\n",
" \"\"\" Get the latest prediction subfolder using the timestamp in the subfolder name\"\"\"\n",
" folders = !gsutil ls $gcs_out_dir\n",
" latest = \"\"\n",
" for folder in folders:\n",
" subfolder = folder.split(\"/\")[-2]\n",
" if subfolder.startswith(\"prediction-\"):\n",
" if subfolder > latest:\n",
" latest = folder[:-1]\n",
" return latest\n",
"\n",
"\n",
"while True:\n",
" response = clients[\"job\"].get_batch_prediction_job(name=batch_job_id)\n",
" if response.state != aip.JobState.JOB_STATE_SUCCEEDED:\n",
" print(\"The job has not completed:\", response.state)\n",
" if response.state == aip.JobState.JOB_STATE_FAILED:\n",
" break\n",
" else:\n",
" folder = get_latest_predictions(\n",
" response.output_config.gcs_destination.output_uri_prefix\n",
" )\n",
" ! gsutil ls $folder/prediction*.jsonl\n",
"\n",
" ! gsutil cat $folder/prediction*.jsonl\n",
" break\n",
" time.sleep(60)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"gs://migration-ucaip-trainingaip-20210301212135/batch_output/prediction-claritin_20210301212135-2021-03-02T01:41:31.705301Z/predictions_00001.jsonl\n",
"{\"instance\":{\"content\":\"gs://migration-ucaip-trainingaip-20210301212135/test.txt\",\"mimeType\":\"text/plain\"},\"prediction\":{\"sentiment\":2}}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aeAz5yPa1sis"
},
"source": [
"## Make online predictions"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "h4_aWo7-1sis"
},
"source": [
"### Prepare data item for online prediction"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "86h1FUtA1sis"
},
"outputs": [],
"source": [
"test_data = ! gsutil cat $IMPORT_FILE | head -n1\n",
"\n",
"test_item = str(test_data[0]).split(\",\")[1]\n",
"test_label = str(test_data[0]).split(\",\")[2]\n",
"\n",
"print((test_item, test_label))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "COwVZtxhJjkW"
},
"source": [
"### [projects.locations.endpoints.create](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.endpoints/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NI50tf4Q1sit"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tdNxDl9U1sit"
},
"outputs": [],
"source": [
"endpoint = {\"display_name\": \"claritin_\" + TIMESTAMP}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.CreateEndpointRequest(parent=PARENT, endpoint=endpoint).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"endpoint\": {\n",
" \"displayName\": \"claritin_20210301212135\"\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "o-3TRQXY1sit"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tha965qB1sit"
},
"outputs": [],
"source": [
"request = clients[\"endpoint\"].create_endpoint(parent=PARENT, endpoint=endpoint)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zNmlwwWh1sit"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "AWpQw1G61sit"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/endpoints/45845236831748096\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "c469d14a26ea"
},
"outputs": [],
"source": [
"# The full unique ID for the endpoint\n",
"endpoint_id = result.name\n",
"# The short numeric ID for the endpoint\n",
"endpoint_short_id = endpoint_id.split(\"/\")[-1]\n",
"\n",
"print(endpoint_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gpnVJS3AJjkW"
},
"source": [
"### [projects.locations.endpoints.deployModel](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.endpoints/deployModel)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fRWgao0Q1siu"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "RV9Ytz4o1siu"
},
"outputs": [],
"source": [
"deployed_model = {\n",
" \"model\": model_id,\n",
" \"display_name\": \"claritin_\" + TIMESTAMP,\n",
" \"automatic_resources\": {\"min_replica_count\": 1, \"max_replica_count\": 1},\n",
"}\n",
"\n",
"traffic_split = {\"0\": 100}\n",
"\n",
"print(\n",
" MessageToJson(\n",
" aip.DeployModelRequest(\n",
" endpoint=endpoint_id,\n",
" deployed_model=deployed_model,\n",
" traffic_split=traffic_split,\n",
" ).__dict__[\"_pb\"]\n",
" )\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"endpoint\": \"projects/116273516712/locations/us-central1/endpoints/45845236831748096\",\n",
" \"deployedModel\": {\n",
" \"model\": \"projects/116273516712/locations/us-central1/models/5497364624833511424\",\n",
" \"displayName\": \"claritin_20210301212135\",\n",
" \"automaticResources\": {\n",
" \"minReplicaCount\": 1,\n",
" \"maxReplicaCount\": 1\n",
" }\n",
" },\n",
" \"trafficSplit\": {\n",
" \"0\": 100\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "J7bV5doB1siu"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "28zuTgn31siu"
},
"outputs": [],
"source": [
"request = clients[\"endpoint\"].deploy_model(\n",
" endpoint=endpoint_id, deployed_model=deployed_model, traffic_split=traffic_split\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Gi-yN6VJ1siv"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_CWhWunf1siv"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"deployedModel\": {\n",
" \"id\": \"6669232913810194432\"\n",
" }\n",
"}\n",
"```\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "629d19cbcf39"
},
"outputs": [],
"source": [
"# The unique ID for the deployed model\n",
"deployed_model_id = result.deployed_model.id\n",
"\n",
"print(deployed_model_id)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6a0-OOQ61siv"
},
"source": [
"### [projects.locations.endpoints.predict](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.endpoints/predict)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ABoH16AE1siw"
},
"source": [
"#### Request"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "qFzxI6uY1siw"
},
"outputs": [],
"source": [
"instances_list = [{\"content\": test_item}]\n",
"instances = [json_format.ParseDict(s, Value()) for s in instances_list]\n",
"\n",
"request = aip.PredictRequest(endpoint=endpoint_id)\n",
"request.instances.append(instances)\n",
"\n",
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"endpoint\": \"projects/116273516712/locations/us-central1/endpoints/45845236831748096\",\n",
" \"instances\": [\n",
" [\n",
" {\n",
" \"content\": \"@freewrytin God is way too good for Claritin\"\n",
" }\n",
" ]\n",
" ]\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5HyneZhf1siw"
},
"source": [
"#### Call"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "mkC_HbE11siw"
},
"outputs": [],
"source": [
"request = clients[\"prediction\"].predict(endpoint=endpoint_id, instances=instances)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9KIx8hQZ1siw"
},
"source": [
"#### Response"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Tq2gITNu1six"
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"predictions\": [\n",
" {\n",
" \"sentiment\": 2.0\n",
" }\n",
" ],\n",
" \"deployedModelId\": \"6669232913810194432\"\n",
"}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "endpoints_undeploymodel:migration,new"
},
"source": [
"### [projects.locations.endpoints.undeployModel](https://cloud.google.com/vertex-ai/docs/reference/rest/v1beta1/projects.locations.endpoints/undeployModel)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KrVZz6Uw_jAp"
},
"source": [
"#### Call\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "endpoints_undeploymodel:migration,new,call"
},
"outputs": [],
"source": [
"request = clients[\"endpoint\"].undeploy_model(\n",
" endpoint=endpoint_id, deployed_model_id=deployed_model_id, traffic_split={}\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "wvFK-kir_jAq"
},
"source": [
"#### Response\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "GvajSw-Y_jAq"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{}\n",
"```\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bQ-VVaSxJjkd"
},
"source": [
"# Cleaning up\r\n",
"\r\n",
"To clean up all GCP resources used in this project, you can [delete the GCP\r\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\r\n",
"\r\n",
"Otherwise, you can delete the individual resources you created in this tutorial."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "ZLFTpeDL1six"
},
"outputs": [],
"source": [
"delete_dataset = True\n",
"delete_model = True\n",
"delete_endpoint = True\n",
"delete_pipeline = True\n",
"delete_batchjob = True\n",
"delete_bucket = True\n",
"\n",
"# Delete the dataset using the Vertex AI fully qualified identifier for the dataset\n",
"try:\n",
" if delete_dataset:\n",
" clients[\"dataset\"].delete_dataset(name=dataset_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the model using the Vertex AI fully qualified identifier for the model\n",
"try:\n",
" if delete_model:\n",
" clients[\"model\"].delete_model(name=model_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the endpoint using the Vertex AI fully qualified identifier for the endpoint\n",
"try:\n",
" if delete_endpoint:\n",
" clients[\"endpoint\"].delete_endpoint(name=endpoint_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the training pipeline using the Vertex AI fully qualified identifier for the training pipeline\n",
"try:\n",
" if delete_pipeline:\n",
" clients[\"pipeline\"].delete_training_pipeline(name=training_pipeline_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the batch job using the Vertex AI fully qualified identifier for the batch job\n",
"try:\n",
" if delete_batchjob:\n",
" clients[\"job\"].delete_batch_prediction_job(name=batch_job_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"if delete_bucket and \"BUCKET_NAME\" in globals():\n",
" ! gsutil rm -r gs://$BUCKET_NAME"
]
}
],
"metadata": {
"colab": {
"name": "UJ8 unified AutoML for natural language with Vertex AI - Text Sentiment Analysis.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}